import {message} from "antd";
import {messages} from "share/common";

export function wrappedRowSelection(rowConfig, callBack) {
  const { limit, parser, rowKey, selectedRowKeys, selectedRows } = rowConfig;
  let _selectedRowKeys = selectedRowKeys || [];
  let _selectedRows = selectedRows || [];

  let findKey = record => {
    return (typeof rowKey === 'string') ? record[rowKey] : rowKey(record)
  };

  let onChange = (selectedRowKeys) => {
    if (limit && selectedRowKeys.length > limit) {
      message.warning(messages('common.max.selected.data',{arg1: limit})/*最多选择 {arg1} 条数据*/)
    } else {
      _selectedRowKeys = selectedRowKeys;
    }
  };

  let onSelect = (record, selected, selectedRows, shouldCallBack = true) => {
    let thisIndex = -1;
    if(selected && limit && _selectedRowKeys.length > limit) {
      return ;
    }
    _selectedRows.map((i, index) => (findKey(i) === findKey(record)) && (thisIndex = index));
    selected && (thisIndex === -1) && (_selectedRows.push(parser ? parser(record) : record));
    !selected && thisIndex > -1 && (_selectedRows.splice(thisIndex, 1));
    shouldCallBack && callBack(_selectedRowKeys, _selectedRows);
  };

  let onSelectAll = (selected, selectedRows, changeRows) => changeRows.map((item, index) => onSelect(item, selected, selectedRows, index === changeRows.length -1));

  return { onChange, onSelect, onSelectAll, selectedRowKeys: _selectedRowKeys }
}
